<script type="text/javascript" src="/js/jqplot/jquery.jqplot.min.js"></script>
<script type="text/javascript" src="/js/jqplot/plugins/jqplot.barRenderer.min.js"></script>
<script type="text/javascript" src="/js/jqplot/plugins/jqplot.pieRenderer.min.js"></script>
<script type="text/javascript" src="/js/jqplot/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script type="text/javascript" src="/js/jqplot/plugins/jqplot.pointLabels.min.js"></script>
<link rel="stylesheet" type="text/css" hrf="/js/jqplot/jquery.jqplot.min.css" />

<script type="text/javascript" src="/js/highcharts/highcharts.js"></script>
<script type="text/javascript" src="/js/highcharts/modules/exporting.js"></script>

<?php slot("page", "list"); ?>

<!--h1>View feedback</h1-->

<?php
    if (count($userSources) == 0) {
        echo "<div class='alert alert-block'><strong>This page allows viewing, analysing & graphing of feedback</strong>, but you currently have no sources configured. Head to the <a href='" . url_for("feedback/setup") . "'>setup</a> page to add your apps.</div>";
    }
    else {
?>
        <div class="row">
            <div class="span3">
                <h3>Filters</h3>
                
                <form method="get" action="<?php echo url_for('feedback/list') ?>">
                    <div class="accordion">
                        <div class="accordion-group">
                            <div class="accordion-heading">
                                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne"><i class="icon-white <?php echo ($sourceIdMixed ? "icon-ok-circle" : "icon-remove-circle") ?>"></i> Sources</a>
                            </div>
                            <div id="collapseOne" class="accordion-body collapse" style="height: 0px; ">
                                <div class="accordion-inner">
                                    <?php foreach ($userSources as $userSource): ?>
                                        <label class="checkbox">
                                            <input type="checkbox" name="sourceId[]" value="<?php echo $userSource->Source->getId(); ?>"
                                                <?php echo (($sourceIdMixed && ((is_object($sourceIdMixed) && is_array($sourceIdMixed->getRawValue()) && in_array($userSource->Source->getId(), $sourceIdMixed->getRawValue())) || $sourceIdMixed == $userSource->Source->getId())) ? "checked" : "") ?> />
                                                <?php echo $userSource->getDisplayName() ?>
                                                <?php echo DisplayHelper::createProviderIconHtml($userSource->Source->getProvider()) ?>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                        <div class="accordion-group">
                            <div class="accordion-heading">
                                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo"><i class="icon-white <?php echo ($ratingStars ? "icon-ok-circle" : "icon-remove-circle") ?>"></i> Ratings</a>
                            </div>
                            <div id="collapseTwo" class="accordion-body collapse" style="height: 0px; ">
                                <div class="accordion-inner">
                                    <select class="span1" name="rating-comparison">
                                        <option value="greater-than" <?php if ($ratingComparison == "greater-than") echo " selected"; ?>>&gt;=</option>
                                        <option value="equal-to" <?php if ($ratingComparison == "equal-to") echo " selected"; ?>>=</option>
                                        <option value="less-than" <?php if ($ratingComparison == "less-than") echo " selected"; ?>>&lt;=</option>
                                    </select>
                                    <input type="text" name="rating-stars" class="input-mini" placeholder="Stars..." value="<?php if ($ratingStars) echo $ratingStars; ?>" />
                                </div>
                            </div>
                        </div>
                        <div class="accordion-group">
                            <div class="accordion-heading">
                                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseThree"><i class="icon-white <?php echo ($dateMode && $dateMode != "all" ? "icon-ok-circle" : "icon-remove-circle") ?>"></i> Dates</a>
                            </div>
                            <div id="collapseThree" class="accordion-body collapse" style="height: 0px; ">
                                <div class="accordion-inner">
                                    <label class="radio"><input type="radio" name="date-mode" id="date-mode-all" value="all" <?php if (!$dateMode || $dateMode == "all") echo "checked=\"checked\""; ?> />All</label>
                                    <label class="radio"><input type="radio" name="date-mode" id="date-mode-this-week" value="this-week" <?php if ($dateMode == "this-week") echo "checked=\"checked\""; ?> />This week</label>
                                    <label class="radio"><input type="radio" name="date-mode" id="date-mode-last-week" value="last-week" <?php if ($dateMode == "last-week") echo "checked=\"checked\""; ?> />Last week</label>
                                    <label class="radio"><input type="radio" name="date-mode" id="date-mode-this-month" value="this-month" <?php if ($dateMode == "this-month") echo "checked=\"checked\""; ?> />This month</label>
                                    <label class="radio"><input type="radio" name="date-mode" id="date-mode-last-month" value="last-month" <?php if ($dateMode == "last-month") echo "checked=\"checked\""; ?> />Last month</label>
                                    <label class="radio"><input type="radio" name="date-mode" id="date-mode-this-year" value="this-year" <?php if ($dateMode == "this-year") echo "checked=\"checked\""; ?> />This year</label>
                                    <label class="radio"><input type="radio" name="date-mode" id="date-mode-this-year" value="last-year" <?php if ($dateMode == "last-year") echo "checked=\"checked\""; ?> />Last year</label>
                                    <label class="radio">
                                        <input type="radio" name="date-mode" id="date-mode-custom" value="custom" <?php if ($dateMode == "custom") echo "checked=\"checked\""; ?> />
                                            <input type="text" class="input-small" name="date-mode-custom-from" placeholder="From..." value="<?php if ($dateMode == "custom" && $fromDate) echo date("Y-m-d", $fromDate); ?>" />
                                             to <input type="text" class="input-small" name="date-mode-custom-to" placeholder="To..." value="<?php if ($dateMode == "custom" && $toDate) echo date("Y-m-d", $toDate); ?>" />
                                            (in "yyyy-mm-dd" format)
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="accordion-group">
                            <div class="accordion-heading">
                                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseFour"><i class="icon-white <?php echo ($name ? "icon-ok-circle" : "icon-remove-circle") ?>"></i> Name</a>
                            </div>
                            <div id="collapseFour" class="accordion-body collapse" style="height: 0px; ">
                                <div class="accordion-inner">
                                    <input type="text" class="" name="name" placeholder="Name..." value="<?php echo ($name ? $name : ""); ?>">
                                </div>
                            </div>
                        </div>
                        <div class="accordion-group">
                            <div class="accordion-heading">
                                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseFive"><i class="icon-white <?php echo ($content ? "icon-ok-circle" : "icon-remove-circle") ?>"></i> Content</a>
                            </div>
                            <div id="collapseFive" class="accordion-body collapse" style="height: 0px; ">
                                <div class="accordion-inner">
                                    <input type="text" class="" name="content" placeholder="Content..." value="<?php echo ($content ? $content : ""); ?>">
                                </div>
                            </div>
                        </div>
                        <div class="accordion-group">
                            <div class="accordion-heading">
                                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseSix"><i class="icon-white <?php echo ($tagIdMixed ? "icon-ok-circle" : "icon-remove-circle") ?>"></i> Tags</a>
                            </div>
                            <div id="collapseSix" class="accordion-body collapse" style="height: 0px; ">
                                <div class="accordion-inner">
                                    <?php foreach ($tags as $tag): ?>
                                        <label class="checkbox">
                                            <input type="checkbox" name="tagId[]" value="<?php echo $tag->getId(); ?>"
                                                <?php echo (($tagIdMixed && ((is_object($tagIdMixed) && is_array($tagIdMixed->getRawValue()) && in_array($tag->getId(), $tagIdMixed->getRawValue())) || $tagIdMixed == $tag->getId())) ? "checked" : "") ?> />
                                                <?php echo $tag->getName() ?>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Update filter</button>
                </form>
            </div>
            
            <div class="span9">
                <h3>Results</h3>
                
                <?php if ($feedbackItems->count() == 0): ?>
                    <div class="alert alert-info">No feedback items found based on your search criteria. Please use the controls on the left to change your search criteria.</div>
                <?php else: ?>
                    <div style="float: right; margin-left: 10px;"><button class="btn" id="export"><i class="icon-download-alt"></i> Export as CSV</button></div>
                    
                    <div class="btn-group" data-toggle="buttons-radio" style="float: right;">
                        <button class="btn active" id="view-list"><i class="icon-th-list"></i> View list</button>
                        <button class="btn" id="view-graph"><i class="icon-signal"></i> View graph</button>
                    </div>
                    
                    <script type="text/javascript">
                        <?php if ($user->isAllowedToExport()) { ?>
                            $("#export").click(function() {
                                $("#export-modal").modal();
                                $('#export-modal').on('shown', function () {
                                    var url = "<?php echo url_for('feedback/exportCsv') ?>?" + "<?php echo $_SERVER["QUERY_STRING"]; ?>";
                                    $("body").append(
                                        $("<iframe />")
                                            .attr("src", url)
                                            .hide()
                                    );
                                });
                            });
                        <?php } else if (!$user->isAllowedToExport() && $user->isEligibleForUpgrade()) { ?>
                            $("#export").click(function() {
                                showUpgradeModal("Sorry, your account type doesn't allow exporting to CSV!");
                            });
                        <?php } else { ?>
                            $("#export").addClass("disabled");
                        <?php } ?>
                        
                    </script>
                    
                    <p class="results-info">Total of <?php echo $feedbackCount ?> feedback items found based on selected filter.</p>
                    
                    <div class="clear" style="height: 10px;"></div>
                    
                    <div id="feedback-list">
                        <?php foreach ($feedbackItems as $feedback): ?>
                            <div class="feedback well" id="feedback-<?php echo $feedback->getId() ?>">
                                
                                <?php echo DisplayHelper::printIconWithRoundedCorners($feedback->Source->getFinalIconUrl()) ?>
                                
                                <div class="date"><?php echo DateHelper::fuzzyDate(strtotime($feedback->getSubmittedDate())) ?></div>
                                <div class="source">
                                    <em><?php
                                        if (isset($userSourceBySourceId[$feedback->getSourceId()])) {
                                            echo ($userSourceBySourceId[$feedback->getSourceId()]->getName() ? $userSourceBySourceId[$feedback->getSourceId()]->getName() : $feedback->Source->getName());
                                        }
                                        else {
                                            echo $feedback->Source->getName();
                                        }
                                    ?></em>
                                    <?php echo DisplayHelper::createProviderIconHtml($feedback->Source->getProvider()) ?>
                                    <?php if ($feedback->getVersion()) echo " <em>(Version " . $feedback->getVersion() . "</em>)" ?>
                                </div>
                                
                                <?php if ($feedback->getRating()): ?><div class="rating"><?php echo DisplayHelper::createRatingHtml($feedback->getRating()) ?></div><?php endif; ?>
                                <div class="title-details">
                                    <?php if ($feedback->getTitle()): ?><span class="title"><?php echo TextHelper::unescape($feedback->getTitle()) ?></span><?php endif; ?>
                                    <span class="name">
                                        by <strong><?php echo TextHelper::unescape($feedback->getName()) ?></strong>
                                        <?php if ($feedback->getDeviceType()): ?> on <?php echo TextHelper::unescape($feedback->getDeviceType()) ?><?php endif; ?>
                                    </span>
                                </div>
                                
                                <div class="content"><em><?php echo TextHelper::unescape($feedback->getContent()) ?></em></div>
                                
                                <div class="tags-container"></div>
                                <div class="tags-button-container"><button class="btn edit-tags"><i class="icon-tags"></i> <span>Edit tags</span></button></div>
                                
                                <div class="clear"></div>
                            </div>
                        <?php endforeach; ?>
                        
                        <div class="pagination pagination-centered">
                            <ul>
                                <?php
                                    $paddingBetweenPaginationItems = 2;
                                    $previousLink = ($currentPage > 1 ? $paginationLinks[$currentPage - 2] : null);
                                    $nextLink = ($currentPage < count($paginationLinks) ? $paginationLinks[$currentPage] : null);
                                    
                                    echo "<li " . (!$previousLink ? "class='disabled'" : "") . "><a href='" . ($previousLink ? $paginationLinks[0] : "#") . "'>&lt;&lt;</a></li>" . PHP_EOL;
                                    echo "<li " . (!$previousLink ? "class='disabled'" : "") . "><a href='" . ($previousLink ? $previousLink : "#") . "'>&lt;</a></li>" . PHP_EOL;
                                    
                                    // Easiest way to only show the necessary page numbers is to do this and then filter out the duplicate or nonsensical ones
                                    
                                    $pageNumbersToAdd = array(
                                        1,
                                        2,
                                        ($currentPage - 2),
                                        ($currentPage - 1),
                                        $currentPage,
                                        ($currentPage + 1),
                                        ($currentPage + 2),
                                        (count($paginationLinks) - 1),
                                        count($paginationLinks)
                                    );
                                    $pageNumbersToAdd = array_unique($pageNumbersToAdd);
                                    sort($pageNumbersToAdd);
                                    
                                    // Show all the sensible resulting pag numbers, and show ellipses in between gaps
                                    
                                    $previousPageNumber = null;
                                    foreach ($pageNumbersToAdd as $pageNumberToAdd) {
                                        if ($pageNumberToAdd > 0 && $pageNumberToAdd <= count($paginationLinks)) {
                                            if ($previousPageNumber && $pageNumberToAdd != ($previousPageNumber + 1)) {
                                                echo "<li class='disabled'><a href='#'>...</a></li>" . PHP_EOL;
                                            }
                                            
                                            echo "<li " . ($currentPage == $pageNumberToAdd ? "class='active'" : "") . "><a href='" . ($currentPage != $pageNumberToAdd ? $paginationLinks[$pageNumberToAdd - 1] : "#") . "'>" . $pageNumberToAdd . "</a></li>" . PHP_EOL;
                                            
                                            $previousPageNumber = $pageNumberToAdd;
                                        }
                                    }
                                    
                                    echo "<li " . (!$nextLink ? "class='disabled'" : "") . "><a href='" . ($nextLink ? $nextLink : "#") . "'>&gt;</a></li>" . PHP_EOL;
                                    echo "<li " . (!$nextLink ? "class='disabled'" : "") . "><a href='" . ($nextLink ? $paginationLinks[count($paginationLinks) - 1] : "#") . "'>&gt;&gt;</a></li>" . PHP_EOL;
                                ?>
                            </ul>
                        </div>
                    </div>
                <?php endif; ?>
                
                <div id="feedback-graph" style="display: none;" class="">
                    
                    <form class="form-horizontal well" onSubmit="return false;">
                        <fieldset>
                            <legend>Chart options</legend>
                            
                            <p>Select your chart type and options to see feedback visualisations.</p>
                            
                            <div class="control-group" id="group-chart-type">
                                <label class="control-label" for="chart-type">Chart type</label>
                                <div class="controls">
                                    <select id="chart-type">
                                        <option value="">(Please select)</option>
                                        <option value="bar">Bar graph</option>
                                        <option value="pie">Pie chart</option>
                                        <option value="line">Line graph (over time)</option>
                                        <option value="scatter">Scatter graph (over time)</option>
                                    </select>
                                </div>
                            </div>
                            <div class="control-group" id="group-chart-x" style="display: none;">
                                <label class="control-label" for="chart-x">X-values</label>
                                <div class="controls">
                                    <select id="chart-x">
                                        <?php if ($allowSourceChart): ?>
                                            <option value="sources">Sources</option>
                                        <?php endif; ?>
                                        <option value="ratings">Ratings</option>
                                    </select>
                                </div>
                            </div>
                            <div class="control-group" id="group-chart-y" style="display: none;">
                                <label class="control-label" for="chart-y">Y-values</label>
                                <div class="controls">
                                    <select id="chart-y">
                                    </select>
                                </div>
                            </div>
                            <div class="control-group" id="group-time-period" style="display: none;">
                                <label class="control-label" for="time-period">Time period</label>
                                <div class="controls">
                                    <select id="time-period">
                                        <option value="day">By day</option>
                                        <option value="month">By month</option>
                                        <option value="year">By year</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-actions">
                                <button class="btn btn-primary" id="view-chart">View chart</button>
                            </div>
                        </fieldset>
                    </form>
                    
                    <div id="chart">
                    </div>
                    
                    <script type="text/javascript">
                        
                        //
                        // Handle the controls
                        //
                        
                        var addSelectOption = function(selectBoxSelector, title, value) {
                            $(selectBoxSelector).append(
                                $("<option />")
                                    .html(title)
                                    .attr("value", value)
                            );
                        };
                        var removeSelectOption = function(selectBoxSelector, value) {
                            $(selectBoxSelector + ">option[value='" + value + "']").remove();
                        };
                        
                        var refreshChartOptionControls = function() {
                            
                            $("#group-chart-x").hide();
                            $("#group-chart-y").hide();
                            $("#group-time-period").hide();
                            
                            var chartType = $("#chart-type").val();
                            if (chartType == "bar" || chartType == "pie") {
                                $("#group-chart-x").show();
                                
                                if (chartType == "bar") {
                                    addSelectOption("#chart-x", "Tags", "tags");
                                }
                                else {
                                    removeSelectOption("#chart-x", "tags");
                                    $("#chart-x>option[value='sources']").attr("selected", true);
                                }
                            }
                            else if (chartType == "line" || chartType == "scatter") {
                                $("#group-chart-y").show();
                                
                                removeSelectOption("#chart-y", "count");
                                removeSelectOption("#chart-y", "average-rating");
                                removeSelectOption("#chart-y", "rating");
                                
                                if (chartType == "scatter") {
                                    addSelectOption("#chart-y", "Rating", "rating");
                                }
                                else {
                                    $("#group-time-period").show();
                                    
                                    addSelectOption("#chart-y", "Total", "count");
                                    addSelectOption("#chart-y", "Average rating", "average-rating");
                                }
                            }
                            
                            if (chartType) {
                                $("#view-chart").removeAttr("disabled");
                            }
                            else {
                                $("#view-chart").attr("disabled", "disabled");
                            }
                        };
                        
                        $("#chart-type").change(refreshChartOptionControls);
                        
                        refreshChartOptionControls();
                        
                        //
                        // Handle running the chart
                        //
                        
                        var filterQueryString = "<?php echo $_SERVER["QUERY_STRING"]; ?>";
                        
                        var cleanseNumber = function(input) {
                            return parseFloat(input);
                        };
                        var cleanseNumberArray = function(input) {
                            var output = [];
                            for (var i = 0; i < input.length; i++) {
                                output.push(cleanseNumber(input[i]));
                            }
                            return output;
                        };
                        
                        $("#view-chart").click(function() {
                            var url = "<?php echo url_for('feedback/chartData') ?>?"
                                + filterQueryString
                                + "&chart-type=" + $("#chart-type").val()
                                + "&chart-x=" + $("#chart-x").val()
                                + "&chart-y=" + $("#chart-y").val()
                                + "&time-period=" + $("#time-period").val();
                            
                            $("#feedback-graph").mask("Loading...");
                            
                            $.getJSON(
                                url,
                                function(data) {
                                    //console.log(data);
                                    
                                    $("#feedback-graph").unmask();
                                    
                                    $('#chart').children().remove();
                                    
                                    var chartConfig = {
                                        chart: {
                                            renderTo: 'chart'
                                        },
                                        xAxis: {},
                                        title: {
                                            text: null
                                        },
                                        tooltip: {},
                                        yAxis: {
                                            min: 0,
                                            title: {
                                               text: data.ySeriesTitle
                                            }
                                        },
                                        series: {}
                                    };
                                    
                                    if ($("#chart-type").val() == "bar") {
                                        chartConfig.chart.type = "bar";
                                        
                                        chartConfig.xAxis.categories = data.labels;
                                        chartConfig.yAxis.allowDecimals = false;
                                        chartConfig.series = [{
                                            name: data.xSeriesTitle,
                                            data: cleanseNumberArray(data.data)
                                        }];
                                    }
                                    else if ($("#chart-type").val() == "line") {
                                        chartConfig.chart.type = "line";
                                        
                                        var labels = [];
                                        var maxLabels = 10;
                                        if (data.labels.length > maxLabels) {
                                            var itemsToSkip = Math.ceil((data.labels.length - maxLabels) / maxLabels);
                                            for (var i = 0; i < data.labels.length; i++) {
                                                if (i == 0 || (i + 1) % itemsToSkip == 0) {
                                                    labels.push(data.labels[i])
                                                }
                                                else {
                                                    labels.push("");
                                                }
                                            }
                                        }
                                        else {
                                            labels = data.labels;
                                        }
                                        
                                        chartConfig.xAxis.categories = labels;
                                        chartConfig.series = [{
                                            name: data.xSeriesTitle,
                                            data: cleanseNumberArray(data.data)
                                        }];
                                    }
                                    else if ($("#chart-type").val() == "scatter") {
                                        chartConfig.chart.type = "scatter";
                                        chartConfig.xAxis.type = 'datetime';
                                        
                                        var cleansedData = [];
                                        $(data.data).each(function(index, element) {
                                            // The first sub-element (the date) neds to be formatted as a JS date, the second
                                            // sub-element (the rating) needs to be an integer so that it shows correctly
                                            
                                            var dateChunks = element[0].split("-");
                                            cleansedData.push([Date.UTC(dateChunks[0], (cleanseNumber(dateChunks[1]) - 1), dateChunks[2]), cleanseNumber(element[1])]);
                                        });
                                        
                                        //chartConfig.xAxis.categories = data.labels;
                                        chartConfig.series = [{
                                            name: data.xSeriesTitle,
                                            data: cleansedData
                                        }];
                                        
                                        chartConfig.tooltip = {
                                            formatter: function() {
                                                return this.y + ' star rating on ' + Highcharts.dateFormat('%e. %b', this.x);
                                            }
                                        };
                                    }
                                    else if ($("#chart-type").val() == "pie") {
                                        // Pie doesn't need a chartConfig.chart.type
                                        
                                        var cleansedData = cleanseNumberArray(data.data);
                                        var pieFormattedData = [];
                                        for (var i = 0; i < cleansedData.length; i++) {
                                            pieFormattedData.push([data.labels[i], cleansedData[i]]);
                                        }
                                        
                                        chartConfig.series = [{
                                            type: "pie",
                                            data: pieFormattedData
                                        }];
                                        
                                        chartConfig.tooltip = {
                                            formatter: function() {
                                                return '<b>'+ this.point.name +'</b>: ' + this.y + ' feedback items (' + Math.round(this.percentage) + '%)';
                                            }
                                        };
                                    }
                                    
                                    var chart = new Highcharts.Chart(chartConfig);
                                }
                            );
                        });
                    </script>
                </div>
                
                <script type="text/javascript">
                    $("#view-list").click(function() {
                        $("#feedback-list").show();
                        $("#feedback-graph").hide();
                    });
                    $("#view-graph").click(function() {
                        $("#feedback-list").hide();
                        $("#feedback-graph").show();
                    });
                    
                    <?php if ($view == "graph"): ?>
                        $("#view-list").removeClass("active");
                        $("#view-graph").addClass("active");
                        $("#feedback-list").hide();
                        $("#feedback-graph").show();
                    <?php endif; ?>
                </script>
            </div>
            
        </div>
<?php } ?>

<script type="text/javascript">
    
    //
    // Data structures
    //
    
    var feedbackItems = <?php
        $feedbackJsonList = array();
        foreach ($feedbackItems as $feedbackItem) {
            $feedbackJsonItem = array(
                "id" => $feedbackItem->getId(),
                "tags" => array()
            );
            foreach ($feedbackItem->FeedbackTag as $feedbackTag) {
                $feedbackJsonItem["tags"][] = $feedbackTag->getTagId();
            }
            $feedbackJsonList[] = $feedbackJsonItem;
        }
        echo json_encode($feedbackJsonList);
    ?>;
    
    var tags = <?php
        $tagJsonList = array();
        foreach ($tags as $tag) {
            $tagJsonList[] = array(
                "id" => $tag->getId(),
                "name" => $tag->getName()
            );
        }
        echo json_encode($tagJsonList);
    ?>;
    
    var availableTags = [];
    $(tags).each(function(index, element) {
        availableTags.push(element.name);
    });
    
    //
    // Methods
    //
    
    var getIdForTag = function(name) {
        var id = null;
        
        $(tags).each(function(index, element) {
            if (element.name == name) {
                id = element.id;
            }
        });
        
        return id;
    };
    var getTagForId = function(id) {
        var name = null;
        
        $(tags).each(function(index, element) {
            if (element.id == id) {
                name = element.name;
            }
        });
        
        return name;
    };
    
    var createTagList = function(tags) {
        var tagsList = $("<ul />")
            .addClass("tags")
            .addClass("tagit");
        
        $(tags).each(function(index, element) {
            var name = getTagForId(element);
            
            if (name) {
                $("<li />")
                    .html(name)
                    .addClass("tagit-choice")
                    .addClass("ui-widget-content")
                    .addClass("ui-state-default")
                    .addClass("ui-corner-all")
                    .addClass("view-mode")
                    .appendTo(tagsList);
            }
        });
        
        return tagsList;
    };
    
    //
    // onReady logic
    // 

    var currentSelectedFeedbackItemId = null;
    var currentSelectedFeedbackTags = null;
    
    $(document).ready(function() {
        $(feedbackItems).each(function(index, element) {
            (function() {
                var feedbackId = element.id;
                var feedbackTags = element.tags;
                
                // Set up the initial tags
                $("#feedback-" + feedbackId + " div.tags-container").append(createTagList(feedbackTags));
                
                // Set up the button handler
                $("#feedback-" + feedbackId + " button.edit-tags").click(function() {
                    
                    if (currentSelectedFeedbackItemId != null && currentSelectedFeedbackItemId == feedbackId) {
                        // We are already in edit mode for this feedback item - the user is clicking the save button
                        
                        var url = "<?php echo url_for('feedback/saveTags') ?>?feedbackId=" + feedbackId;
                        
                        var assignedTags = $("#feedback-" + feedbackId + " ul.tags").tagit("assignedTags");
                        $(assignedTags).each(function(index, element) {
                            var assignedTagId = getIdForTag(element);
                            if (assignedTagId) {
                                url += "&tags[]=" + assignedTagId;
                            }
                            else {
                                url += "&tags[]=" + element;
                            }
                        });
                        
                        $("#feedback-" + feedbackId).mask("Saving...");
                        
                        $.getJSON(
                            url,
                            function(data) {
                                
                                $("#feedback-" + feedbackId).unmask();
                                
                                // Add any newly added tags to the master lists
                                $(data.newTags).each(function(index, element) {
                                    tags.push({
                                        id: element.id,
                                        name: element.name
                                    })
                                    availableTags.push(element.name);
                                });
                                
                                // Save the new list of tags for this feedback item
                                feedbackTags = data.feedbackTags;
                                
                                // Refresh the UI - leave edit mode
                                currentSelectedFeedbackItemId = null;
                                currentSelectedFeedbackTags = null;
                                $("#feedback-" + feedbackId + " button.edit-tags span").html("Edit tags");
                                $("#feedback-" + feedbackId + " button.edit-tags i").removeClass("icon-white");
                                $("#feedback-" + feedbackId + " button.edit-tags").removeClass("btn-primary");
                                $("#feedback-" + feedbackId + " ul.tags").remove();
                                $("#feedback-" + feedbackId + " div.tags-container").append(createTagList(feedbackTags));
                            }
                        );
                    
                        currentSelectedFeedbackItemId = feedbackId;
                        currentSelectedFeedbackTags = feedbackTags;
                    }
                    else {
                        // User wishes to start editing this feedback item
                        
                        if (currentSelectedFeedbackItemId != null) {
                            // First remove any other feedback item from edit mode
                            
                            $("#feedback-" + currentSelectedFeedbackItemId + " button.edit-tags span").html("Edit tags");
                            $("#feedback-" + currentSelectedFeedbackItemId + " button.edit-tags i").removeClass("icon-white");
                            $("#feedback-" + currentSelectedFeedbackItemId + " button.edit-tags").removeClass("btn-primary");
                            $("#feedback-" + currentSelectedFeedbackItemId + " ul.tags").remove();
                            $("#feedback-" + currentSelectedFeedbackItemId + " div.tags-container").append(createTagList(currentSelectedFeedbackTags));
                        }
                        
                        currentSelectedFeedbackItemId = feedbackId;
                        currentSelectedFeedbackTags = feedbackTags;
                        
                        $("#feedback-" + feedbackId + " button.edit-tags span").html("Save");
                        $("#feedback-" + feedbackId + " button.edit-tags i").addClass("icon-white");
                        $("#feedback-" + feedbackId + " button.edit-tags").addClass("btn-primary");
                        $("#feedback-" + feedbackId + " ul.tags").tagit({
                            availableTags: availableTags
                        });
                        
                        $("#feedback-" + feedbackId + " ul.tags li.tagit-new input").focus();
                    }
                });
            })();
        });
    });

</script>

<!-- Export popup -->
<div class="modal hide fade" id="export-modal" style="margin-top: -200px;">
    <div class="modal-header">
        <h3>Export as CSV</h3>
    </div>
    <div class="modal-body main">
        <p>Your export is being prepared. <em>Please be patient</em> - depending on your filter criteria this may take up to a minute. Your export will begin downloading when ready.</p>
        <p>Please note that exports can only show a maximum of 1,000 feedback items. If you wish to export more items, please use the filter criteria to do multiple exports.</p>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal">Done</button>
    </div>
</div>
